package com.sctvcloud.dongqu.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.base.BaseFragment;
import com.sctvcloud.dongqu.beans.FocusColumn;
import com.sctvcloud.dongqu.beans.HomeEvent;
import com.sctvcloud.dongqu.ui.activities.ColumnEditActivity;
import com.sctvcloud.dongqu.ui.activities.LoginActivity;
import com.sctvcloud.dongqu.ui.adapter.PlateFormPagerAdapter;
import com.sctvcloud.dongqu.ui.dialog.ChooseCityFuncFragment;
import com.sctvcloud.dongqu.utils.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/6/19 0019.
 * 首页
 */
public class PlatFormFragment extends BaseFragment {

    private final String ColumnUrl = "sctv/index.json";
    private static PlatFormFragment instance;

    @BindView(R.id.home_tablay)
    protected SlidingTabLayout home_tablay;
    @BindView(R.id.home_content_vp)
    protected ViewPager home_content_vp;

    @BindView(R.id.home_top_lay_tab)
    protected ViewGroup tabLay;


    @BindView(R.id.home_no_data_ct)
    protected CustomFontTextView no_data;
    private PlateFormPagerAdapter homePagerAdapter;
    private ArrayList<FocusColumn> list = new ArrayList<FocusColumn>();
    private ArrayList<FocusColumn>  thisColumnList = new ArrayList<FocusColumn>();
    public static final int REQUEST_CODE = 1;
    public static final String COLUMN_DATA = "column_data";
    private Gson gson;
    private ChooseCityFuncFragment chooseCityFuncFragment;
    private ChooseCityFuncFragment arouseAppFuncFragment;
    private ChooseCityFuncFragment toInstallFuncFragment;
    private static final String IS_START = "IS_START";
    public static final String NET_TAG = "chooseCityFuncFragment";
    private List<FocusColumn> al_column;
    private List<FocusColumn> ot_column;
    private String playBackUrl, searchUrl, contributeUrl;
    private boolean isShowLZ = false;//是否是显示泸州市的新闻
    private FragmentManager fragmentManager;
    private boolean isShowCityFunc = false;

    @BindView(R.id.home_content_ll)
    protected LinearLayout content_ll;
    @BindView(R.id.title_top_back)
    protected ImageView backImg;
    private String lastColumnId = "";//切换到其他模块时，记录首页的栏目ID

    private String cityCode = "";
    private static final String IS_EXHCNAGE = "IS_EXCHANGE";
    private static final String LOCATION_CITY = "LOCATION_CITY";
    protected static final int CODE_REQUEST_LOGIN = 303;

    public static PlatFormFragment getInstance() {
        return instance;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_platform, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        fragmentManager = this.getChildFragmentManager();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化请求栏目数据
        initData();
        initViews();
        instance = this;

    }

    private void initViews(){

        backImg.setVisibility(View.GONE);

    }

    @Override
    public void onResume() {
        super.onResume();

        if(home_content_vp.getCurrentItem()==2){
            if (!UserManager.isLoginS()) {
                home_content_vp.setCurrentItem(0);

            }
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ColumnBaseFragment cbf = getCurrentFragment();
        if (!hidden) {
            Cache.getInstance().setCurrentChannelId(Cache.getInstance().getCurrentColumnId("报料", "微平台"));

        }else{

        }
        if (cbf != null) {
            cbf.setParentShowing(!hidden);
            cbf.onHiddenChanged(hidden);
        }
    }

    protected void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    private void initData(){

        FocusColumn apply = new FocusColumn();
        apply.setChannelName("民生诉求");
        apply.setChannelType(String.valueOf(PlateFormPagerAdapter.TYPE_APPLY));

//        FocusColumn reward = new FocusColumn();
//        reward.setChannelName("举报有奖");
//        reward.setChannelType(String.valueOf(PlateFormPagerAdapter.TYPE_REWARD));


        FocusColumn share = new FocusColumn();
        share.setChannelName("新闻报料");
        share.setChannelType(String.valueOf(PlateFormPagerAdapter.TYPE_SHARE));

//        FocusColumn report = new FocusColumn();
//        report.setChannelName("互动分享");
//        report.setChannelType(String.valueOf(PlateFormPagerAdapter.TYPE_HUDONG));


        FocusColumn applyall = new FocusColumn();
        applyall.setChannelName("我的诉求");
        applyall.setChannelType(String.valueOf(PlateFormPagerAdapter.TYPE_APPLY_ALL));


        list.add(apply);
//        list.add(reward);
        list.add(share);
        list.add(applyall);

        setData(list);
    }

    /**
     * 加载 首页中的各个栏目页面
     *
     * @param fChannels
     */
    private void setData(List<FocusColumn> fChannels) {
        if (ListUtils.isListValued(fChannels)) {
            content_ll.setVisibility(View.VISIBLE);
            no_data.setVisibility(View.GONE);

            boolean b = true;
            int s = -1;
            if (homePagerAdapter == null) {
                homePagerAdapter = new PlateFormPagerAdapter(getChildFragmentManager(), list);
                setAdapterTopHeiht(true);
                home_content_vp.setAdapter(homePagerAdapter);
                home_content_vp.setOffscreenPageLimit(1);
                home_content_vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageSelected(int position) {
                        if(position==2){
                            if (!UserManager.isLoginS()) {
                                toLogin();
                            }
                        }
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
                home_tablay.setViewPager(home_content_vp);
                s = homePagerAdapter.getCount();
            } else {
                s = homePagerAdapter.getCount();
                setAdapterTopHeiht(true);
                homePagerAdapter.setData(list);
                b = s != homePagerAdapter.getCount();
            }
//            home_tablay.setOnTabSelectListener(this);
            refreshColumnTab(b);
            home_tablay.setTextUnselectColor(getResources().getColor(R.color.color_666666));
            home_tablay.setTextSelectColor(getResources().getColor(R.color.colorBlack22));
            home_tablay.setChangeSize(true);
        } else {
            no_data.setVisibility(View.VISIBLE);
            content_ll.setVisibility(View.GONE);
        }


    //    home_tablay.setChangeSize(true);
        home_tablay.notifyDataSetChanged();
        home_tablay.setTabPadding(0);
        home_tablay.setTabSpaceEqual(true);
    }

    /**
     * 获取当前正显示的Fragment
     *
     * @return
     */
    public ColumnBaseFragment getCurrentFragment() {
        if (home_content_vp == null || homePagerAdapter == null || homePagerAdapter.getCount() == 0) {
            return null;
        }
        ColumnBaseFragment cbf = homePagerAdapter.getFragmentByPos(home_content_vp.getCurrentItem());
        JLog.e("ffsf " + cbf);

        return cbf;
    }

    /**
     * 刷新栏目
     *
     * @param data
     */
    private void refreshData(Intent data) {
        ArrayList<FocusColumn> al_data = (ArrayList<FocusColumn>) data.getSerializableExtra(ColumnEditActivity.COLUMN);
        for (int i = 0; i < al_data.size(); i++) {
            if (!al_data.get(i).isChoice()) {
                al_data.remove(i);
                i--;
            }
        }
        if (al_data.size() != 0) {
            if (homePagerAdapter != null) {
                if (ListUtils.isListValued(al_data)) {
                    thisColumnList = new ArrayList<>();
                    thisColumnList.addAll(al_data);
                }
                int s = homePagerAdapter.getCount();
                homePagerAdapter.setData(al_data);
                home_tablay.notifyDataSetChanged();
//                JLog.e("===  will refresh data   " + homePagerAdapter.getCount()+"   s="+s);
                refreshColumnTab(s != homePagerAdapter.getCount());
            }

        }
    }

    /**
     * 刷新栏目在首页的标签
     *
     * @param b
     */
    private void refreshColumnTab(boolean b) {
        int size = homePagerAdapter.getCount();
        if (size == 0 || !b) {
            return;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            topLay.setVisibility(View.GONE);
//            tabLay.setVisibility(View.GONE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//            topLay.setVisibility(View.VISIBLE);
//            tabLay.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean hasShowPlayer() {
        BaseFragment bf = getCurrentFragment();
        return bf != null && bf.hasShowPlayer();
    }

    @OnClick(value = { R.id.home_no_data_ct})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.home_no_data_ct:
                showProgress("数据正在加载中...");
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if(requestCode==CODE_REQUEST_LOGIN){
                home_content_vp.setCurrentItem(0);
            }

        }

        if (data == null) {
            return;
        }
        final int pos = data.getIntExtra(ColumnEditActivity.SELECT_POS, 0);
        if (pos > 0) {
            refreshData(data);
            final int currentPos = home_content_vp.getCurrentItem();
            home_content_vp.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (currentPos != pos) {
                        home_content_vp.setCurrentItem(pos);
                    } else {
                        home_content_vp.setCurrentItem(currentPos);
                    }
                }
            }, 200);
        } else {
            refreshData(data);
        }

    }

    @Override
    public boolean onBackPressed() {
        ColumnBaseFragment f = getCurrentFragment();
        if (f != null && f.onBackPressed()) {
            return true;
        }
        return super.onBackPressed();
    }

    private Gson initGson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }


    private void setAdapterTopHeiht(boolean isNewInstance) {
        if (isNewInstance) {
                    homePagerAdapter.setTopHeight(tabLay.getHeight());
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onjump(HomeEvent messageEvent) {
        if (null != messageEvent ) {
            if (messageEvent.getPosition()==0) {
                home_content_vp.setCurrentItem(0);
            }else if(messageEvent.getPosition()==1){
                home_content_vp.setCurrentItem(1);
            }
        }

    }

}
